package com.kb.erp.service.impl;

import cn.smallbun.screw.core.util.StringUtils;
import com.kb.erp.domain.ConFiles;
import com.kb.erp.domain.NPCBContract;
import com.kb.erp.domain.RFQContract;
import com.kb.erp.mapper.sqlServer.ConFilesMapper;
import com.kb.erp.mapper.sqlServer.NPCBContractMapper;
import com.kb.erp.mapper.sqlServer.RFQContractMapper;
import com.kb.erp.service.ContractFillingService;
import com.kb.erp.util.MessageUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ContractFilingServiceImpl implements ContractFillingService {

    @Autowired
    private ConFilesMapper conFilesMapper;
    @Autowired
    private NPCBContractMapper NpcbContractMapper;
    @Autowired
    private RFQContractMapper RfqContractMapper;

    @Override
    public void getcontractfile() {
        FTPClient ftpClient = new FTPClient();
        String server = "file.kbsems01.com";
        int port = 21;
        String user = "kbsys";
        String pass = "Kb741!@#";


        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, pass);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            LocalDate currentDate = LocalDate.now();
            // 拼接字符串
            String fileUrl = "/conf/" + currentDate.getYear() + "/" + currentDate.getMonthValue() + "/" + currentDate.getDayOfMonth();
            String[] split = fileUrl.split("/");
            for (String str : split) {
                if(StringUtils.isBlank(str)) {
                    continue;
                }
                if (!ftpClient.changeWorkingDirectory(str)) {
                    //System.err.println("不存在");
                    boolean makeDirectory = ftpClient.makeDirectory(str);
                    boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(str);
                    //System.err.println(str + "创建：" + makeDirectory + ";切换：" + changeWorkingDirectory);
                } else {
                    //System.err.println("存在");
                }
            }
            List<ConFiles> ConFilesList = conFilesMapper.selectTopList(50);
            if (CollectionUtils.isEmpty(ConFilesList)) {
                return;
            } else {
                for (ConFiles confile : ConFilesList) {
                    Byte[] bytes = confile.getConFile();
                    if (bytes == null || bytes.length == 0 ) {
                        continue;
                    }
                    byte[] byteArray = new byte[bytes.length];
                    for (int i = 0; i < bytes.length; i++) {
                        byteArray[i] = bytes[i].byteValue();
                    }
                    InputStream inputStream = new ByteArrayInputStream(byteArray);
                    boolean success = ftpClient.storeFile(confile.getFileName(), inputStream);
                    inputStream.close();

                    if (success) {
                        confile.setFileLink(currentDate.getYear() + "\\" + currentDate.getMonthValue() + "\\" + currentDate.getDayOfMonth()+"\\"+confile.getFileName());
                        confile.setFilingDate(new Date());
                        confile.setUpFlag(2);
                        confile.setConFile(null);
                        conFilesMapper.updateConFiles(confile);
                        //System.out.println("合同归档成功");
                        if(confile.getConType().equals("PCB"))
                        {
                            RFQContract RfqContract = RfqContractMapper.getRfqCon(confile.getCustCode(),confile.getConNum());
                            RfqContract.setUpload_status("已归档");
                            RfqContractMapper.updateRfqUploadStatus(RfqContract);
                            //System.out.println("PCB合同状态更新");
                        }
                        else if (confile.getConType().equals("NPCB"))
                        {
                            NPCBContract NpcbContract = NpcbContractMapper.getNpcbCon(confile.getCustCode(),confile.getConNum());
                            NpcbContract.setUpload_status("已归档");
                            NpcbContractMapper.updateNpcbUploadStatus(NpcbContract);
                            //System.out.println("NPCB合同状态更新");
                        }
                        log.info("文件上传成功！");

                    } else {
                        log.info("文件上传失败！");
                    }
                }
            }
            ftpClient.logout();
        } catch (Exception e) {
            MessageUtil.sentMessageToAssistant("18571", e.getMessage());
            log.info(e.getMessage());
            XxlJobHelper.log(e.getMessage());
            throw new RuntimeException(e);

        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }

    }
}
















